<template>
  <div class="exercises-container">
    <h1 class="page-title">习题管理</h1>

    <div class="exercise-controls">
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索习题"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        />
        <el-select v-model="difficultyFilter" placeholder="难度" clearable class="filter-select">
          <el-option label="简单" value="easy" />
          <el-option label="中等" value="medium" />
          <el-option label="困难" value="hard" />
        </el-select>
        <el-select v-model="typeFilter" placeholder="类型" clearable class="filter-select">
          <el-option label="选择题" value="choice" />
          <el-option label="填空题" value="fill" />
          <el-option label="问答题" value="qa" />
          <el-option label="编程题" value="code" />
        </el-select>
      </div>
      <el-button type="primary" @click="showAddExerciseDialog">添加习题</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredExercises"
      border
      stripe
      style="width: 100%"
      class="exercises-table"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="exercise-detail">
            <div class="detail-item" v-if="props.row.description">
              <strong>题目描述：</strong>
              <div class="detail-content" v-html="props.row.description"></div>
            </div>
            <div class="detail-item" v-if="props.row.type === 'choice'">
              <strong>选项：</strong>
              <div class="options-list">
                <div v-for="(option, index) in props.row.options" :key="index" class="option-item">
                  <span :class="{ 'correct-answer': index === props.row.answer }">
                    {{ String.fromCharCode(65 + index) }}. {{ option }}
                  </span>
                </div>
              </div>
            </div>
            <div class="detail-item" v-if="props.row.answer && props.row.type !== 'choice'">
              <strong>答案：</strong>
              <div class="detail-content">{{ props.row.answer }}</div>
            </div>
            <div class="detail-item" v-if="props.row.analysis">
              <strong>解析：</strong>
              <div class="detail-content" v-html="props.row.analysis"></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="题目" min-width="300">
        <template #default="scope">
          <div class="exercise-title-cell">
            <el-tag size="small" v-if="scope.row.type === 'choice'" type="success">选择题</el-tag>
            <el-tag size="small" v-else-if="scope.row.type === 'fill'" type="warning"
              >填空题</el-tag
            >
            <el-tag size="small" v-else-if="scope.row.type === 'qa'" type="info">问答题</el-tag>
            <el-tag size="small" v-else-if="scope.row.type === 'code'" type="danger">编程题</el-tag>
            <span class="exercise-title">{{ scope.row.title }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.difficulty === 'easy'
                ? 'success'
                : scope.row.difficulty === 'medium'
                  ? 'warning'
                  : 'danger'
            "
            size="small"
          >
            {{
              scope.row.difficulty === 'easy'
                ? '简单'
                : scope.row.difficulty === 'medium'
                  ? '中等'
                  : '困难'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="previewExercise(scope.row)">预览</el-button>
          <el-button size="small" type="primary" @click="editExercise(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteExercise(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="totalExercises > 0"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalExercises"
      :page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      class="pagination"
    />

    <!-- 添加/编辑习题对话框 -->
    <el-dialog
      v-model="exerciseDialogVisible"
      :title="isEditing ? '编辑习题' : '添加习题'"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="currentExercise"
        label-width="100px"
        :rules="exerciseRules"
        ref="exerciseForm"
      >
        <el-form-item label="题目类型" prop="type">
          <el-radio-group v-model="currentExercise.type">
            <el-radio-button label="choice">选择题</el-radio-button>
            <el-radio-button label="fill">填空题</el-radio-button>
            <el-radio-button label="qa">问答题</el-radio-button>
            <el-radio-button label="code">编程题</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题目标题" prop="title">
          <el-input v-model="currentExercise.title" placeholder="请输入题目标题" />
        </el-form-item>

        <el-form-item label="题目描述">
          <el-input
            v-model="currentExercise.description"
            type="textarea"
            rows="4"
            placeholder="可选，输入题目的详细描述，支持富文本"
          />
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="currentExercise.difficulty" placeholder="请选择难度">
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>

        <!-- 选择题特有的选项 -->
        <template v-if="currentExercise.type === 'choice'">
          <el-divider content-position="left">选项设置</el-divider>

          <div v-for="(option, index) in currentExercise.options" :key="index" class="option-input">
            <el-form-item
              :label="`选项 ${String.fromCharCode(65 + index)}`"
              :prop="`options.${index}`"
            >
              <div class="option-input-group">
                <el-input
                  :model-value="currentExercise.options ? currentExercise.options[index] : ''"
                  @update:model-value="
                    (val: string) =>
                      currentExercise.options && (currentExercise.options[index] = val)
                  "
                  placeholder="请输入选项内容"
                />
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeOption(index)"
                  v-if="currentExercise.options && currentExercise.options.length > 2"
                ></el-button>
              </div>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" plain @click="addOption">添加选项</el-button>
          </el-form-item>

          <el-form-item label="正确答案" prop="answer">
            <el-radio-group v-model="currentExercise.answer">
              <el-radio v-for="(_, index) in currentExercise.options" :key="index" :label="index">{{
                String.fromCharCode(65 + index)
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <!-- 非选择题答案 -->
        <el-form-item v-if="currentExercise.type !== 'choice'" label="参考答案" prop="answer">
          <el-input
            v-model="currentExercise.answer"
            type="textarea"
            rows="3"
            placeholder="请输入参考答案"
          />
        </el-form-item>

        <el-form-item label="答案解析">
          <el-input
            v-model="currentExercise.analysis"
            type="textarea"
            rows="3"
            placeholder="可选，输入答案解析，帮助学生理解"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="exerciseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveExercise">保存</el-button>
      </template>
    </el-dialog>

    <!-- 预览习题对话框 -->
    <el-dialog v-model="previewDialogVisible" title="习题预览" width="650px">
      <div class="exercise-preview" v-if="selectedExercise">
        <div class="preview-header">
          <h3 class="preview-title">{{ selectedExercise.title }}</h3>
          <div class="preview-meta">
            <el-tag
              :type="
                selectedExercise.difficulty === 'easy'
                  ? 'success'
                  : selectedExercise.difficulty === 'medium'
                    ? 'warning'
                    : 'danger'
              "
              size="small"
            >
              {{
                selectedExercise.difficulty === 'easy'
                  ? '简单'
                  : selectedExercise.difficulty === 'medium'
                    ? '中等'
                    : '困难'
              }}
            </el-tag>
            <el-tag
              size="small"
              :type="
                selectedExercise.type === 'choice'
                  ? 'success'
                  : selectedExercise.type === 'fill'
                    ? 'warning'
                    : selectedExercise.type === 'qa'
                      ? 'info'
                      : 'danger'
              "
            >
              {{
                selectedExercise.type === 'choice'
                  ? '选择题'
                  : selectedExercise.type === 'fill'
                    ? '填空题'
                    : selectedExercise.type === 'qa'
                      ? '问答题'
                      : '编程题'
              }}
            </el-tag>
          </div>
        </div>

        <div class="preview-description" v-if="selectedExercise.description">
          <div v-html="selectedExercise.description"></div>
        </div>

        <div class="preview-options" v-if="selectedExercise.type === 'choice'">
          <div
            v-for="(option, index) in selectedExercise.options"
            :key="index"
            class="preview-option"
          >
            <div class="option-label">{{ String.fromCharCode(65 + index) }}</div>
            <div class="option-content">{{ option }}</div>
          </div>
        </div>

        <el-divider>答案与解析</el-divider>

        <div class="preview-answer">
          <strong>参考答案：</strong>
          <span v-if="selectedExercise.type === 'choice'">
            {{ String.fromCharCode(65 + selectedExercise.answer) }}.
            {{ selectedExercise.options && selectedExercise.options[selectedExercise.answer] }}
          </span>
          <div v-else>{{ selectedExercise.answer }}</div>
        </div>

        <div class="preview-analysis" v-if="selectedExercise.analysis">
          <strong>解析：</strong>
          <div v-html="selectedExercise.analysis"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const route = useRoute()
const taskId = route.params.id

// 习题数据结构
interface Exercise {
  id: string
  title: string
  description?: string
  type: 'choice' | 'fill' | 'qa' | 'code'
  difficulty: 'easy' | 'medium' | 'hard'
  options?: string[]
  answer: any // 可能是索引或字符串
  analysis?: string
  createTime: Date
}

// 示例数据
const exercises = ref<Exercise[]>([
  {
    id: '1',
    title: '以下哪项不是Vue.js的核心功能？',
    description: 'Vue.js是一个流行的前端框架，请选择不属于Vue.js核心功能的选项。',
    type: 'choice',
    difficulty: 'easy',
    options: ['响应式数据绑定', '组件化开发', '虚拟DOM', '原生移动应用开发'],
    answer: 3,
    analysis:
      'Vue.js的核心功能包括响应式数据绑定、组件化开发和虚拟DOM。原生移动应用开发是React Native或Flutter等框架的特性。',
    createTime: new Date('2023-09-10'),
  },
  {
    id: '2',
    title: '简述Vue组件的生命周期',
    type: 'qa',
    difficulty: 'medium',
    answer:
      'Vue组件的生命周期主要包括创建、挂载、更新和销毁四个阶段。各个阶段的钩子函数依次为：beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeUnmount、unmounted。',
    analysis:
      '理解组件的生命周期对于在适当的时机执行代码至关重要，例如在mounted中进行数据请求，在beforeUnmount中清理定时器等。',
    createTime: new Date('2023-09-15'),
  },
  {
    id: '3',
    title: '请实现一个函数，接收一个数组，返回数组中的最大值',
    description:
      '不使用Math.max方法，手动实现一个函数findMax，接收一个数字数组作为参数，返回数组中的最大值。',
    type: 'code',
    difficulty: 'hard',
    answer: `function findMax(arr) {
  if (!arr || arr.length === 0) return null;
  let max = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }
  return max;
}`,
    analysis:
      '这个问题主要考察数组遍历和比较，通过遍历数组并不断更新最大值来解决。需要注意边界情况处理，如空数组。',
    createTime: new Date('2023-09-20'),
  },
])

// 列表过滤与分页
const loading = ref(false)
const searchQuery = ref('')
const difficultyFilter = ref('')
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalExercises = ref(3)

// 添加/编辑习题相关
const exerciseDialogVisible = ref(false)
const isEditing = ref(false)
const currentExercise = ref<Partial<Exercise>>({
  title: '',
  description: '',
  type: 'choice',
  difficulty: 'medium',
  options: ['', ''],
  answer: 0,
  analysis: '',
})
const exerciseForm = ref<FormInstance>()
const exerciseRules = reactive<FormRules>({
  title: [{ required: true, message: '请输入题目标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  difficulty: [{ required: true, message: '请选择难度级别', trigger: 'change' }],
  answer: [{ required: true, message: '请提供参考答案', trigger: 'blur' }],
})

// 预览相关
const previewDialogVisible = ref(false)
const selectedExercise = ref<Exercise | null>(null)

// 计算属性：过滤后的习题列表
const filteredExercises = computed(() => {
  let result = exercises.value

  // 关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      (e) =>
        e.title.toLowerCase().includes(query) ||
        (e.description && e.description.toLowerCase().includes(query)),
    )
  }

  // 难度过滤
  if (difficultyFilter.value) {
    result = result.filter((e) => e.difficulty === difficultyFilter.value)
  }

  // 类型过滤
  if (typeFilter.value) {
    result = result.filter((e) => e.type === typeFilter.value)
  }

  return result
})

// 初始化
onMounted(() => {
  fetchExercisesForTask()
})

// 方法
const fetchExercisesForTask = () => {
  loading.value = true
  // 实际项目中从API获取数据
  console.log(`获取任务ID为 ${taskId} 的习题列表`)
  // 模拟API请求
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchExercisesForTask()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchExercisesForTask()
}

const showAddExerciseDialog = () => {
  isEditing.value = false
  currentExercise.value = {
    title: '',
    description: '',
    type: 'choice',
    difficulty: 'medium',
    options: ['', ''],
    answer: 0,
    analysis: '',
  }
  exerciseDialogVisible.value = true
}

const editExercise = (exercise: Exercise) => {
  isEditing.value = true
  // 深拷贝避免直接修改原对象
  currentExercise.value = JSON.parse(JSON.stringify(exercise))
  exerciseDialogVisible.value = true
}

const saveExercise = async () => {
  if (!exerciseForm.value) return

  await exerciseForm.value.validate((valid, fields) => {
    if (valid) {
      // 实际项目中调用API保存数据
      if (isEditing.value) {
        // 更新已有习题
        const index = exercises.value.findIndex((e) => e.id === currentExercise.value.id)
        if (index !== -1) {
          exercises.value[index] = {
            ...currentExercise.value,
            createTime: exercises.value[index].createTime,
          } as Exercise
        }
        ElMessage.success('习题更新成功')
      } else {
        // 添加新习题
        const newExercise: Exercise = {
          ...(currentExercise.value as any),
          id: Date.now().toString(),
          createTime: new Date(),
        }
        exercises.value.unshift(newExercise)
        ElMessage.success('习题添加成功')
      }
      exerciseDialogVisible.value = false
    } else {
      console.log('表单验证失败:', fields)
    }
  })
}

const deleteExercise = (exercise: Exercise) => {
  ElMessageBox.confirm(`确定要删除习题 "${exercise.title}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 实际项目中调用API删除数据
      exercises.value = exercises.value.filter((e) => e.id !== exercise.id)
      ElMessage.success('习题已删除')
    })
    .catch(() => {
      // 取消删除
    })
}

const previewExercise = (exercise: Exercise) => {
  selectedExercise.value = exercise
  previewDialogVisible.value = true
}

const addOption = () => {
  if (currentExercise.value.options) {
    currentExercise.value.options.push('')
  }
}

const removeOption = (index: number) => {
  if (currentExercise.value.options && currentExercise.value.options.length > 2) {
    currentExercise.value.options.splice(index, 1)
    // 如果删除的是当前选中的答案或在当前答案之前，需要调整答案
    if (typeof currentExercise.value.answer === 'number') {
      if (index === currentExercise.value.answer) {
        currentExercise.value.answer = 0 // 重置为第一个选项
      } else if (index < currentExercise.value.answer) {
        currentExercise.value.answer--
      }
    }
  }
}

// 工具函数
const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}
</script>

<style scoped>
.exercises-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 24px;
  color: #333;
}

.exercise-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-filter {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.filter-select {
  width: 120px;
}

.exercises-table {
  margin-bottom: 20px;
}

.exercise-title-cell {
  display: flex;
  align-items: center;
}

.exercise-title {
  margin-left: 8px;
}

.exercise-detail {
  padding: 15px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-content {
  margin-top: 5px;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.options-list {
  margin-top: 5px;
}

.option-item {
  padding: 5px 0;
}

.correct-answer {
  color: #67c23a;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.option-input {
  margin-bottom: 10px;
}

.option-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 预览样式 */
.exercise-preview {
  padding: 10px;
}

.preview-header {
  margin-bottom: 20px;
}

.preview-title {
  margin-bottom: 10px;
}

.preview-meta {
  display: flex;
  gap: 10px;
}

.preview-description {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-options {
  margin-bottom: 20px;
}

.preview-option {
  display: flex;
  margin-bottom: 10px;
}

.option-label {
  flex: 0 0 30px;
  font-weight: bold;
}

.option-content {
  flex: 1;
}

.preview-answer {
  margin-bottom: 15px;
}

.preview-analysis {
  margin-top: 15px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}
</style>
